<?php

/////////////////////// 通用函数 ///////////////////////////
class Util
{
    static function make_str_replace($str, $html_filter = true)
    {//字符串替换函数，主要用于替换掉串中不安全字符使其可用于Sql语句中
        //$str = trim( $str );
        //$str = addslashes( $str );
        $str = str_replace("\'", "’", $str);
        $str = str_replace("+", "＋", $str);
        $str = str_replace("*", "＊", $str);
        $str = str_replace("=", "＝", $str);
        $str = str_replace("<", "＜", $str);
        $str = str_replace(">", "＞", $str);
        $str = str_replace("&lt;", "＜", $str);
        $str = str_replace("&gt;", "＞", $str);
        $str = str_replace("&#60;", "＜", $str);
        $str = str_replace("&#62;", "＞", $str);
        $str = str_replace("&", "＆", $str);
        $str = str_replace("&#38;", "＆", $str);
        $str = str_replace("&amp;", "＆", $str);
        $str = str_replace("'", "‘", $str);
        $str = str_replace('"', "“", $str);
        $str = str_replace("SELECT", "ＳＥＬＥＣＴ", $str);
        $str = str_replace("INSERT", "ＩＮＳＥＲＴ", $str);
        $str = str_replace("UPDATE", "ＵＰＤＡＴＥ", $str);
        $str = str_replace("DELETE", "ＤＥＬＥＴＥ", $str);
        $str = str_replace("INTO", "ＩＮＴＯ", $str);
        $str = str_replace("LOAD_FILE", "ＬＯＡＤ＿ＦＩＬＥ", $str);
        $str = str_replace("OUTFILE", "ＯＵＴＦＩＬＥ", $str);
        $str = str_replace("select", "ＳＥＬＥＣＴ", $str);
        $str = str_replace("insert", "ＩＮＳＥＲＴ", $str);
        $str = str_replace("update", "ＵＰＤＡＴＥ", $str);
        $str = str_replace("delete", "ＤＥＬＥＴＥ", $str);
        $str = str_replace("into", "ＩＮＴＯ", $str);
        $str = str_replace("load_file", "ＬＯＡＤ＿ＦＩＬＥ", $str);
        $str = str_replace("outfile", "ＯＵＴＦＩＬＥ", $str);
        $str = str_replace("Select", "ＳＥＬＥＣＴ", $str);
        $str = str_replace("Insert", "ＩＮＳＥＲＴ", $str);
        $str = str_replace("Update", "ＵＰＤＡＴＥ", $str);
        $str = str_replace("Delete", "ＤＥＬＥＴＥ", $str);
        $str = str_replace("Union", "ＵＮＩＯＮ", $str);
        $str = str_replace("Into", "ＩＮＴＯ", $str);
        $str = str_replace("Load_File", "ＬＯＡＤ＿ＦＩＬＥ", $str);
        $str = str_replace("OutFile", "ＯＵＴＦＩＬＥ", $str);
        $str = str_replace("\'", "＼", $str);
        $str = str_replace("\/\*", "＼＼＊", $str);
        $str = str_replace("\*", "＼＊", $str);
        $str = str_replace("\.\.\/", "＼．＼．＼", $str);
        $str = str_replace("\.\/", "＼．＼", $str);
        if ($html_filter) $str = htmlspecialchars($str);
        $str = preg_replace('/[\x00-\x08\x0b\x0c\x0e-\x1f]/', '', $str);
        return $str;
    }

    //针对数字进行排序
    static function array_sort($arr, $keys, $type = 'DESC')
    {
        if (!empty($arr) && trim($keys) <> "")
        {
            foreach ($arr as $key => $row)
            {
                $gettmp[$key] = $row[$keys];
            }
            if ($type == "DESC")
            {
                array_multisort($gettmp, SORT_DESC, $arr);
            }
            else
            {
                array_multisort($gettmp, SORT_ASC, $arr);
            }
        }
        return $arr;
    }

    static function sortmddata($array, $by, $order, $type)
    {//数组排序 $test = sortmddata($strMemo,'CreateTime','DESC','str');
        //$array: the array you want to sort
        //$by: the associative array name that is one level deep
        ////example: name
        //$order: ASC or DESC
        //$type: num or str
        if (trim($array) <> "" && trim($by) <> "" && trim($order) <> "" && trim($type) <> "")
        {
            $sortby = "sort$by"; //This sets up what you are sorting by

            $firstval = current($array); //Pulls over the first array

            $vals = array_keys($firstval); //Grabs the associate Arrays

            foreach ($vals as $init)
            {
                $keyname = "sort$init";
                $$keyname = array();
            }
            //This was strange because I had problems adding
            //Multiple arrays into a variable variable
            //I got it to work by initializing the variable variables as arrays
            //Before I went any further

            foreach ($array as $key => $row)
            {

                foreach ($vals as $names)
                {
                    $keyname = "sort$names";
                    $test = array();
                    $test[$key] = $row[$names];
                    $$keyname = array_merge($$keyname, $test);

                }

            }

            //This will create dynamic mini arrays so that I can perform
            //the array multisort with no problem
            //Notice the temp array... I had to do that because I
            //cannot assign additional array elements to a
            //varaiable variable

            if ($order == "DESC")
            {
                if ($type == "num")
                {
                    array_multisort($$sortby, SORT_DESC, SORT_NUMERIC, $array);
                }
                else
                {
                    array_multisort($$sortby, SORT_DESC, SORT_STRING, $array);
                }
            }
            else
            {
                if ($type == "num")
                {
                    array_multisort($$sortby, SORT_ASC, SORT_NUMERIC, $array);
                }
                else
                {
                    array_multisort($$sortby, SORT_ASC, SORT_STRING, $array);
                }
            }

            //This just goed through and asks the additional arguments
            //What they are doing and are doing variations of
            //the multisort

            return $array;
        }
        else
        {
            return $array;
        }
    }

    //分页计算
    static function page_sum($Total, $pagelist)
    {
        $intSum = 0;
        $intSum = round($Total / $pagelist + 0.49);
        return $intSum;
    }

    static function showpic($strpicurl, $inttype)
    {//显示图片
        //0=原图;1=160x160;2=116x116;3=100x100;4=60x60
        if ($strpicurl == "")
        {//头像是空
            //$strpicurl = "/images/none/".$inttype.".gif";
        }
        else
        {
            $is_aliyun = strpos($strpicurl, 'aliyuncs.com') > 0;
            if (!$is_aliyun)
            {
                $strpicurl = str_replace("s", "", $strpicurl);
                $strpicurl = str_replace("S", "", $strpicurl);
            }
            if ($inttype == 1)
            {//1=160x160
                if ($is_aliyun) $strpicurl .= '?x-oss-process=image/resize,m_mfit,h_160,w_160/quality,q_80';
                else $strpicurl = str_replace(".jpg", "s.jpg", $strpicurl);
            }
            else if ($inttype == 2)
            {//2=116x116
                if ($is_aliyun) $strpicurl .= '?x-oss-process=image/resize,m_mfit,h_116,w_116/quality,q_80';
                else $strpicurl = str_replace(".jpg", "ss.jpg", $strpicurl);
            }
            else if ($inttype == 3)
            {//3=100x100
                if ($is_aliyun) $strpicurl .= '?x-oss-process=image/resize,m_mfit,h_100,w_100/quality,q_80';
                else $strpicurl = str_replace(".jpg", "sss.jpg", $strpicurl);
            }
            else if ($inttype == 4)
            {//4=60x60
                if ($is_aliyun) $strpicurl .= '?x-oss-process=image/resize,m_mfit,h_60,w_60/quality,q_80';
                else $strpicurl = str_replace(".jpg", "ssss.jpg", $strpicurl);
            }
            else if ($inttype == 5)
            {//5=50x50
                if ($is_aliyun) $strpicurl .= '?x-oss-process=image/resize,m_mfit,h_50,w_50/quality,q_80';
                else $strpicurl = str_replace(".jpg", "sssss.jpg", $strpicurl);
            }
            else if ($inttype == 6)
            {//6=32x32
                if ($is_aliyun) $strpicurl .= '?x-oss-process=image/resize,m_mfit,h_32,w_32/quality,q_80';
                else $strpicurl = str_replace(".jpg", "ssssss.jpg", $strpicurl);
            }
            else if ($inttype == 7)
            {//7=390x390
                if ($is_aliyun) $strpicurl .= '?x-oss-process=image/resize,m_mfit,h_390,w_390/quality,q_80';
                else $strpicurl = str_replace(".jpg", "sssssss.jpg", $strpicurl);
            }
        }

        return $strpicurl;
    }

    static function make_rand($intmin, $intmax)
    {//产生随机数
        $seedarray = microtime();
        $seedstr = split(" ", $seedarray, 5);
        $seed = $seedstr[0] * 100000;
        srand($seed);
        $strmemo = rand($intmin, $intmax);
        return $strmemo;
    }

    static function logpagelogs($inttype, $strpage, $inttime)
    {//记录页面超时记录：inttype：0=表示页面；1=表示SQL语句；strpage=页面名称；inttime=执行时间
        if ($inttype == 1)
        {
            error_log($strpage . ";" . $inttime . ";" . date("Y-m-d H:i:s") . "\n", 3, "/www/htdocs/okwww/app/logs/SQLOut_" . date("Ymd") . ".txt");
        }
        else if ($inttype == 2)
        {
            error_log($strpage . ";" . $inttime . ";" . date("Y-m-d H:i:s") . "\n", 3, "/www/htdocs/okwww/app/logs/Data_" . date("Ymd") . ".txt");
        }
        else if ($inttype == 3)
        {
            error_log($strpage . ";" . $inttime . ";" . date("Y-m-d H:i:s") . "\n", 3, "/www/htdocs/okwww/app/logs/OrderLogs_" . date("Ymd") . ".txt");
        }
        else
        {
            error_log($strpage . ";" . $inttime . ";" . date("Y-m-d H:i:s") . "\n", 3, "/www/htdocs/okwww/app/logs/PageOut_" . date("Ymd") . ".txt");
        }
    }

    static function format_num_two($strnum)
    {
        $strnum = $strnum * 100;
        $strnum = intval($strnum + 0.1);
        $strnum = $strnum / 100;
        return $strnum;
    }

    //查看图片是否适合
    static function MakeUploadPic($files)
    {
        $str_err_memo = 0;
        $file_tyle = $files['type'];
        $file_zise = $files['size'];
        $file_type_arr = array('image/gif', 'image/x-png', 'image/jpg', 'image/pjpeg', 'image/jpeg', 'image/bmp');
        if ($file_zise == 0 && trim($file_tyle) == "")
        {
            $str_err_memo = 2;    // "上传文件不能大于2M";
        }
        else if (!in_array($file_tyle, $file_type_arr))
        {
            $str_err_memo = 1;    //"上传文件类型只能为:png,jpeg,jpg,gif";
        }
        else if (($file_zise / 1024) > 12048)
        {
            $str_err_memo = 2;    // "上传文件不能大于2M";
        }
        return $str_err_memo;
    }

    static function generate_code($length = 4)
    {
        return mt_rand(pow(10, ($length - 1)), pow(10, $length) - 1);
    }

    static function fetch_real_ip()
    {//获取用户ID
        if (isset($_SERVER["HTTP_X_FORWARDED_FOR"]) && preg_match_all('/(\d{1,3}\.){3}\d{1,3}/s', $_SERVER['HTTP_X_FORWARDED_FOR'], $mat))
        {
            foreach ($mat[0] AS $ip)
            {
                //得到第一个非内网的IP地址
                if (!preg_match("/^(?:10|172\.16|192\.168)\./", $ip))
                {
                    return $ip;
                }
            }
            return $ip;
        }
        elseif (isset($_SERVER["HTTP_FROM"]) && preg_match('/(?:\d{1,3}\.){3}\d{1,3}/', $_SERVER["HTTP_FROM"]))
        {
            return $_SERVER["HTTP_FROM"];
        }
        else
            return $_SERVER['REMOTE_ADDR'];
    }

    static function csv_export($filename, $header, $content, $columns = array())
    {
        set_time_limit(0);
        header('Content-Type: application/vnd.ms-excel');
        //处理中文文件名
        $agent = $_SERVER["HTTP_USER_AGENT"];
        if (preg_match("/MSIE/", $agent)) {
            header('Content-Disposition: attachment; filename="' . rawurlencode($filename) . '"');
        } else if (preg_match("/Firefox/", $agent)) {
            header("Content-Disposition: attachment; filename*=\"utf8''" . $filename . '"');
        } else {
            header('Content-Disposition: attachment; filename="' . $filename . '"');
        }
        header('Cache-Control: max-age=0');
        $fp = fopen('php://output', 'a');

        if ($header)
        {
            foreach ($header as $i => $v)
            {
                $header[$i] = iconv('utf-8', 'gbk', $v);
            }
            fputcsv($fp, $header);
        }
        if ($content)
        {
            $cnt = 0;
            $limit = 10000;

            foreach ($content as $data)
            {
                $cnt++;
                if ($limit == $cnt)
                {
                    ob_flush();
                    flush();
                    $cnt = 0;
                }

                $row = array();
                if ($columns)
                {
                    foreach ($columns as $column)
                    {
                        if (isset($column['formatter']))
                        {
                            $value = $column['formatter']($data[$column['db']], $data);
                        }
                        else
                        {
                            $value = $data[$column['db']];
                        }
                        $row[] = iconv('utf-8', 'gbk', $value);
                    }
                }
                else
                {
                    foreach ($data as $value)
                    {
                        $row[] = iconv('utf-8', 'gbk', $value);
                    }
                }
                fputcsv($fp, $row);
                unset($row);
            }
        }
        fclose($fp);
    }
}
